package model

import (
	"encoding/json"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
)

type Admin struct {
	gorm.Model
	ANo       string
	APassword string
}

func Register(cpo *gin.Context) {
	DB := GetDB()

	username := cpo.PostForm("username")
	password := cpo.PostForm("password")

	if len(username) < 5 {
		cpo.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422, "msg": "用户名过短",
		})
		return
	}

	if len(password) < 5 {
		cpo.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422, "msg": "密码过短",
		})
		return
	}

	if isidexist(DB, username) {
		cpo.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422, "msg": "用户名已存在",
		})
		return
	}

	newAdmin := Admin{ANo: username, APassword: password}

	DB.Create(&newAdmin)

	cpo.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功!",
	})
}

func Login(cpo *gin.Context) {
	DB := GetDB()
	b, _ := cpo.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	username := m["username"]
	password := m["password"]

	if len(username) < 5 {
		cpo.JSON(200, gin.H{
			"code": 422, "msg": "用户名过短",
			"username": username,
		})
		return
	}

	if len(password) < 5 {
		cpo.JSON(200, gin.H{
			"code": 422, "msg": "密码过短",
		})
		return
	}

	var admin Admin
	DB.Where("a_no = ?", username).First(&admin)
	if admin.ID == 0 {
		cpo.JSON(200, gin.H{
			"code": 422, "msg": "账户不存在",
		})
		return
	}
	//判断正确
	if admin.APassword != password {
		cpo.JSON(200, gin.H{
			"code": 422, "msg": "密码错误",
		})
		return

	}
	print(len(username))
	//返回结果
	cpo.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
}

func isidexist(db *gorm.DB, username string) bool {
	var admin Admin
	db.Where("a_no = ?", username).First(&admin)
	if admin.ID != 0 {
		return true
	}
	return false
}
